package com.aiti.lulian.controller;

import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.constant.MessageCodeConstant;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.*;
import com.aiti.lulian.entity.CardEnterpriseCircle;
import com.aiti.lulian.entity.CardEnterpriseCircleApplication;
import com.aiti.lulian.entity.CardEnterpriseCircleUserCard;
import com.aiti.lulian.entity.newCard.CardBaseInfo;
import com.aiti.lulian.mapper.newCard.CardPersonalBaseInfoMapper;
import com.aiti.lulian.service.CardEnterpriseCircleApplicationService;
import com.aiti.lulian.service.CardEnterpriseCircleService;
import com.aiti.lulian.service.CardEnterpriseCircleUserCardService;
import com.aiti.lulian.vo.CardEnterpriseCircleApplicationVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 名片名企圈表 前端控制器
 * </p>
 *
 * @author 
 * @since 2025-08-20
 */
@RestController
@RequestMapping("/card-enterprise-circle")
public class CardEnterpriseCircleController extends WebController {

    @Autowired
    private CardEnterpriseCircleService circleService;
    @Autowired
    private CardEnterpriseCircleApplicationService circleApplicationService;
    @Autowired
    private CardPersonalBaseInfoMapper cardPersonalBaseInfoMapper;
    @Autowired
    private CardEnterpriseCircleUserCardService circleUserCardService;

    @PostMapping("/save")
    public Message saveCircle(@RequestBody @Validated CardEnterpriseCircleDto dto){
        return circleService.saveCircle(dto);
    }

    @PutMapping("/editIntroduction")
    public Message editIntroduction(@RequestBody CardEnterpriseCircleDto dto){
        return circleService.editCircleIntroduction(dto);
    }

    @GetMapping("/page")
    Message circleList(CardEnterpriseCircleDto dto){
        Page page = startPage(dto);
        return circleService.circleList(page, dto);

    }

    @GetMapping("/activeCircleList")
    Message activeCircleList(CardEnterpriseCircleDto dto){
        Page page = startPage(dto);
        return circleService.activeCircleList(page, dto);

    }


    @GetMapping("/detail")
    Message detail(CardEnterpriseCircleDetailDto dto){
        return circleService.detail(dto);

    }

    @GetMapping("/circleLabels")
    Message circleLabels(@RequestParam("circleId") String circleId, @RequestParam(value = "type", defaultValue = "2") Integer type) {
        return circleService.circleLabels(circleId, type);

    }

    /**
     * “圈子成员-标签配置”
     * 保存标签配置
     */
    @PutMapping("/saveLabel")
    public Message saveLabel(@RequestBody CardEnterpriseCircleDto dto) {
        CardEnterpriseCircle circle = circleService.getById(dto.getBaseId());
        if (circle == null) {
            return Message.fail("圈子不存在");
        }
        return circleService.saveLabel(dto);
    }

    /**
     * "编辑圈子资料"
     * 查询圈子基础资料
     */
    @GetMapping("/getBaseInfo")
    public Message getCircleBaseInfo(@RequestParam("circleId") String circleId) {
        return circleService.getCircleBaseInfo(circleId);
    }

    /**
     * “设置主理人”
     * 获取圈子当前主理人或候选主理人列表
     */
    @GetMapping("/getMemberList")
    public Message getMemberList(CardEnterpriseCircleUserCardDto dto) {
        CardEnterpriseCircle circle = circleService.getById(dto.getCircleId());
        if (circle == null) {
            return Message.fail("圈子不存在");
        }
        Page<CardEnterpriseCircleUserCard> page = startPage(dto);
        List<Map<String, Object>> list = circleService.getMemberList(dto, page);
        return Message.success(getPageResult(list, dto.getPageNum(), dto.getPageSize(), page.getTotal()));
    }

    /**
     * “设置主理人”
     * 设置或移除主理人
     */
    @PutMapping("/setManager")
    public Message setManager(@RequestBody CardEnterpriseCircleUserCardDto dto) {
        // 校验操作权限
        Message message = verifyPermissions(dto.getOperatorCardId(), dto.getCircleId());
        if (!MessageCodeConstant.MSG_SUCCESS_CODE.equals(message.getCode())) {
            return message;
        }
        List<String> baseIds = dto.getBaseIds();
        if (baseIds == null || baseIds.isEmpty()) {
            return Message.fail("请选择成员");
        }
        String type = dto.getType();
        if (!("0".equals(type) || "1".equals(type))) {
            return Message.fail("操作无效");
        }
        return circleService.setManager(dto);
    }

    /**
     * “圈子公告”
     * 获取当前圈子的公告
     */
    @GetMapping("/getAnnouncement")
    public Message getAnnouncement(@RequestParam("circleId") String circleId) {
        CardEnterpriseCircle circle = circleService.getById(circleId);
        if (circle == null) {
            return Message.fail("圈子不存在");
        }
        return Message.success(circle.getAnnouncement());
    }

    /**
     * “圈子公告”
     * 更新圈子的公告
     */
    @PutMapping("/updateAnnouncement")
    public Message updateAnnouncement(@RequestBody CardEnterpriseCircleDto dto) {
        String circleId = dto.getBaseId();
        CardEnterpriseCircle circle = circleService.getById(circleId);
        if (circle == null) {
            return Message.fail("圈子不存在");
        }
        // 校验操作权限
        Message message = verifyPermissions(dto.getUpdaterCardId(), circleId);
        if (!MessageCodeConstant.MSG_SUCCESS_CODE.equals(message.getCode())) {
            return message;
        }
        return circleService.updateAnnouncement(dto);
    }

    /**
     * “加入申请”
     * 查询圈子的加入申请列表
     */
    @GetMapping("/getApplicationList")
    public Message getApplicationList(CardEnterpriseCircleApplicationDto dto) {
        Page<CardEnterpriseCircleApplication> page = startPage(dto);
        List<CardEnterpriseCircleApplicationVo> list = circleApplicationService.getApplicationList(dto, page);
        return Message.success(getPageResult(list, dto.getPageNum(), dto.getPageSize(), page.getTotal()));
    }

    /**
     * “加入申请”
     * 审批加入申请
     */
    @PutMapping("/approveApplication")
    public Message approveApplication(@RequestBody CardEnterpriseCircleApplicationDto dto) {
        CardEnterpriseCircleApplication circleApplication = circleApplicationService.getById(dto.getBaseId());
        // 校验操作权限
        Message message = verifyPermissions(dto.getApproverCardId(), circleApplication.getCircleId());
        if (!MessageCodeConstant.MSG_SUCCESS_CODE.equals(message.getCode())) {
            return message;
        }
        if (!(dto.getStatus() == 1 || dto.getStatus() == 2)) {
            return Message.fail("审批无效");
        }
        if (dto.getStatus() == 2 && dto.getRejectType() == null) {
            return Message.fail("请选择拒绝类型");
        }
        if (dto.getStatus() == 2 && !(dto.getRejectType() == 0 || dto.getRejectType() == 1 || dto.getRejectType() == 2)) {
            return Message.fail("拒绝类型无效");
        }
        return circleApplicationService.approveApplication(dto);
    }

    /**
     * 校验操作权限
     * @param operatorCardId 操作人名片ID
     * @param circleId 圈子ID
     */
    private Message verifyPermissions(String operatorCardId, String circleId) {
        CardBaseInfo operatorBaseInfo = cardPersonalBaseInfoMapper.selectById(operatorCardId);
        if (operatorBaseInfo == null) {
            return Message.fail("名片信息失效");
        }
        CardEnterpriseCircleUserCard circleUserCard = circleUserCardService.getOne(new LambdaQueryWrapper<CardEnterpriseCircleUserCard>().eq(CardEnterpriseCircleUserCard::getCircleId, circleId).eq(CardEnterpriseCircleUserCard::getCardId, operatorCardId).eq(CardEnterpriseCircleUserCard::getIsDelete, 0));
        if (circleUserCard == null) {
            return Message.fail("非圈子成员，不可操作");
        }
        if (!("1".equals(circleUserCard.getType()) || "2".equals(circleUserCard.getType()))) {
            return Message.fail("非圈主或主理人，不可操作");
        }
        return Message.success();
    }

    @PostMapping("/joinCircle")
    public Message joinCircle(@RequestBody @Validated CardEnterpriseJoinCircleDto dto){
        return circleService.joinCircle(dto);
    }

    /**
     * 判断当前登录人的名片是否属于该圈子的主理人或圈主
     */
    @GetMapping("/isCircleMember")
    public Message isCircleMember(@RequestParam("cardId") String cardId, @RequestParam("circleId") String circleId){
        return Message.success(circleService.isCircleMember(cardId, circleId));
    }
}
